# Import Baidu AI SDK
from aip import AipOcr
import cv2
from keras.preprocessing.image import img_to_array
from keras.models import load_model
from myUtil import parse_result, isFakePlate
import numpy as np
import os
import pandas as pd
# Initialize Baidu API client
# APP_ID = 'your-app-id'
APP_ID = '115531234'
# API_KEY = 'your-api-key'
API_KEY = 'lywEwPTuA44Xq0MGet1m3GZJ'
# SECRET_KEY = 'your-secret-key'
SECRET_KEY = 'UAMBChlvYID7x9fMr9MKPVxEU7BhGULw'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])

#vehicle_info_database = pd.read_csv('vehicle-database.csv')
cwd_path = os.getcwd()
cfg_path = cwd_path + "/cfg/yolov3-voc.cfg"
weights_path = cwd_path + "/cfg/yolov3-voc_final.weights"
data_path = cwd_path + "/cfg/voc.data"

VEHICLE_WIDTH = 28
VEHICLE_HEIGHT = 28
v_color_model_path = cwd_path + "/cfg/vehicle_color.hdf5" #
v_type_model_path = cwd_path + "/cfg/vehicle_type.hdf5"

global vehicle_info_database,net,meta


# Define a function to recognize the plate number using Baidu OCR API
def recognize_plate_online(image_path):
    # Read the image
    with open(image_path, 'rb') as img_file:
        image = img_file.read()

    # Call Baidu OCR API
    result = client.licensePlate(image)
    
    if 'words_result' in result:
        plateNo = result['words_result']['number']
        return plateNo
    else:
        return None

def predict(imgPath, vehicle_info_database):
    predictResult = "未识别"
    plateNo = "未识别"
    carBrandZh = "未识别"
    original_image = cv2.imread(imgPath)
    
    v_color_model = load_model(v_color_model_path)
    v_type_model = load_model(v_type_model_path)
    
    # Load and predict the car's bounding box (use pre-trained YOLO or similar)

    # Let's assume the detection box and process them as before
    # import subprocess
    # import json
    #
    # # curl 命令
    # curl_command = [
    #     'curl',
    #     '-X', 'POST',
    #     'http://localhost:8090/detect',
    #     '-F', 'file=@/Users/jackiezheng/liushi/FindFakePlateVehicle-web/test.jpg'
    # ]
    #
    # try:
    #     # 运行 curl 命令
    #     result = subprocess.run(curl_command, capture_output=True, text=True, check=True)
    #
    #     # 打印状态码（curl 成功时总是返回 0）
    #     print(f"Command executed with return code: {result.returncode}")
    #
    #     # 打印输出
    #     print("Response:")
    #     print(result.stdout)
    #
    #     # 尝试解析 JSON 响应
    #     try:
    #         json_response = json.loads(result.stdout)
    #         print("Parsed JSON response:")
    #         print(json.dumps(json_response, ensure_ascii=False, indent=2))
    #     except json.JSONDecodeError:
    #         print("Response is not valid JSON")
    #
    # except subprocess.CalledProcessError as e:
    #     print(f"Command failed with return code {e.returncode}")
    #     print("Error output:")
    #     print(e.stderr)
    #
    # except Exception as e:
    #     print(f"An error occurred: {e}")

    # print(f"predict_result_dict before: {predict_result_dict}")

    # predict_result_dict = {"bbox": {"height": 499.37078857421875, "width": 547.970703125, "x": 677.2782592773438, "y": 427.50067138671875},
    #   "confidence": 0.9998480677604675, "label": "\u96ea\u4f5b\u5170"}

    predict_result_dict = [{
        "bbox": {"height": 499.37078857421875, "width": 547.970703125, "x": 677.2782592773438, "y": 427.50067138671875},
        "confidence": 0.9998480677604675, "label": "\u96ea\u4f5b\u5170"}]

    print(f"predict_result_dict: {predict_result_dict}")
    result_dict = parse_result(predict_result_dict) # Result post-processing

    for i in range(result_dict["b_box_num"]):
        x1_min = result_dict["detection_boxes"][i][0]
        y1_min = result_dict["detection_boxes"][i][1]
        x1_max = result_dict["detection_boxes"][i][2]
        y1_max = result_dict["detection_boxes"][i][3]
        carBrandZh = result_dict["detection_classes"][i] # Vehicle brand

        # Extract the lower 1/3 of the detected vehicle for plate detection
        left = x1_min
        top = int(y1_min + (y1_max - y1_min) * 0.67)
        right = x1_max
        bottom = y1_max
        crop_image = original_image[top:bottom, left:right]
        
        # Save cropped image temporarily
        temp_img_path = "temp_plate_image.jpg"
        cv2.imwrite(temp_img_path, crop_image)

        # 截取汽车检测框的下面1/3部分，作为车牌检测的子区域。调用车牌识别，准确率和计算速度有保证
        left = x1_min
        top = int(y1_min + (y1_max - y1_min) * 0.67)
        right = x1_max
        bottom = y1_max
        crop_image = original_image[top:bottom, left:right]
        grayImg = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY)
        roi_img = cv2.resize(grayImg, (VEHICLE_WIDTH, VEHICLE_HEIGHT))
        roi_img = roi_img.astype("float") / 255.0
        roi_img = img_to_array(roi_img)
        roi_img = np.expand_dims(roi_img, axis=0)
        (bus, car, minibus, truck) = v_type_model.predict(roi_img)[0]
        v_type_result = {"bus": bus, "car": car, "minibus": minibus, "truck": truck}
        v_type_label = max(v_type_result, key=v_type_result.get)

        (black, blue, brown, green, red, silver, white, yellow) = v_color_model.predict(roi_img)[0]
        v_color_result = {"black": black, "blue": blue, "brown": brown, "green": green, "red": red,
                          "silver": silver, "white": white, "yellow": yellow}
        v_color_label = max(v_color_result, key=v_color_result.get)

        # Use Baidu OCR API to recognize the plate number
        plateNo = recognize_plate_online(temp_img_path)

        if plateNo:
            inputCarInfo = [plateNo, carBrandZh]

            # Check if it's a fake plate by comparing it with the vehicle database
            isFake, true_car_brand = isFakePlate(inputCarInfo, vehicle_info_database)
            if isFake:
               predictResult = "这是一辆套牌车" 
            else:
               predictResult = "这是一辆正常车"    
        else:
            plateNo = "未识别"
            predictResult = "车牌未识别，无法判定" 
            
    return plateNo, v_type_label, v_color_label, carBrandZh, predictResult

if __name__ == '__main__':
    # 测试用图片路径
    image_path = 'test.jpg'  # 将 'test.jpg' 替换为实际图片路径
    vehicle_info_database = pd.read_csv('vehicle-database.csv')
    # 调用离线识别函数
    # res = recognize_plate_online(image_path)
    # print(f"res: {res}")

    plate_no, v_type, v_color, car_brand, predict_result = predict(image_path, vehicle_info_database)
    print(f"plate_no {plate_no}")
